package utils

/*
*

	中位值滤波
	多线程不安全
*/
type FilterMiddle struct {
	max_n int32
	lst   *DLinklist
}

func NewFilterMiddle(N int32) *FilterMiddle {
	rval := &FilterMiddle{lst: NewDlinklist(), max_n: N}
	return rval
}

func (this *FilterMiddle) Push(v float64) {
	if this.lst.Count() >= this.max_n {
		node := this.lst.RemoveFirst()
		if node != nil {
			node.release2Pool()
		}
	}
	node := NewDlinknodeFromPool()
	node.Value = v
	this.lst.Append(node)
}

func (this *FilterMiddle) Count() int32 {
	return this.lst.cnt
}

func (this *FilterMiddle) CurrentValue() float64 {
	var sorted []interface{}
	this.lst.Range(func(val interface{}) bool {
		sorted = AppendSliceSorted(sorted, val, func(m, v interface{}) bool {
			return v.(float64) < m.(float64)
		})
		return true
	})
	if len(sorted) == 0 {
		return 0
	}

	return sorted[(len(sorted)-1)/2].(float64)
}

func (this *FilterMiddle) Cleanup() {
	for {
		node := this.lst.RemoveFirst()
		if node != nil {
			node.release2Pool()
		} else {
			break
		}
	}
}
